﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Fis.Win.Forms
{
    public partial class RightsInfoForm : EditForm
    {
        public RightsInfoForm()
        {
            InitializeComponent();
        }

        public override void InitializeBinding()
        {
            var d = ViewModel["viewData"] as DataTable;
            ViewModel["Action"] = ViewState.ToString();

            treeList1.DataSource = d;
            treeList1.RefreshDataSource();
            treeList1.ExpandAll();
        }

        public override void InitializeViewUI()
        {
            iSaveNew.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }

        protected override bool SaveProcess()
        {
            var d = ViewModel["viewData"] as DataTable;
            SetNodeSelectedValue(treeList1.Nodes);

            return (ViewProvider.ExecuteUpdate(ViewModel));
        }

        void GetNodeSelectedValue(DevExpress.XtraTreeList.Nodes.TreeListNodes nodes)
        {
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode n in nodes)
            {
                var value = n.GetValue("FVALUE").ToString();
                n.Checked = (value.Equals("1"));

                if (n.HasChildren)
                    GetNodeSelectedValue(n.Nodes);
            }
        }

        void SetNodeSelectedValue(DevExpress.XtraTreeList.Nodes.TreeListNodes nodes)
        {
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode n in nodes)
            {
                n.SetValue("FVALUE", n.Checked ? 1 : 0);
                n.SetValue("FUSERID", ViewModel["userid"]);

                if (n.HasChildren)
                    SetNodeSelectedValue(n.Nodes);
            }
        }

        private void RightsInfoForm_Load(object sender, EventArgs e)
        {
            GetNodeSelectedValue(treeList1.Nodes);
        }


        //bool isNodeLock = false;
        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            //上级节点点击，下级全选
            if (e.Node.HasChildren)
            {
                foreach (DevExpress.XtraTreeList.Nodes.TreeListNode n in e.Node.Nodes)
                {
                    n.Checked = e.Node.Checked;
                    if (n.HasChildren)
                    {
                        treeList1_AfterCheckNode(sender, new DevExpress.XtraTreeList.NodeEventArgs(n));
                    }
                }
            }

        }
    }
}
